

#include <iostream>
#include <cmath>
#include <vector>
#include <iomanip>

#include "Exception.hpp"
#include "TableDataStore.hpp"
#include "Xvt.hpp"
#include "Vector.hpp"
#include "MJD.hpp"
#include "MiscMath.hpp"
#include "YDSTime.hpp"
#include "StringUtils.hpp"

using namespace gpstk;
using namespace gpstk::StringUtils;

#define debug 0

namespace gpstk
{
    void TableDataStore::loadFile(std::string filename)
    {
       ifstream input(filename.c_str());
       if (!input)
       {
          FileMissingException
          fe ( "Cannot Open xyz-formatted file: " + filename );
          GPSTK_THROW(fe);
       }
       
       bool ok(true);
       
       string line;
       
       while( input.peek() != EOF )
       {
          getline( input, line );
    
          if(debug)
              cout << "data line:" << line << endl;
    
          vector<string> dataVec = split(line, " ");
    
          int year, doy;
          double second;
    
          year = asInt(dataVec[0]);
          doy  = asInt(dataVec[1]);
          second = asDouble(dataVec[2]);
    
    
          if(debug)
              cout << year << " "
                   << doy << " "
                   << second << " "
                   << endl;
    
          YDSTime yds(year, doy, second);
          CommonTime epoch = yds.convertToCommonTime();
    
          epochData[epoch] = dataVec;
          
       }
       
       input.close();
       
       if( !ok )
       {
          FileMissingException fe( filename + "is corrupted..." );
          GPSTK_THROW(fe);
       }
       
    } // END of "loadPositionFile"
    
    
    double TableDataStore::getValue(CommonTime& epoch, int col)
    {
    
        epoch.setTimeSystem(TimeSystem::Unknown);
    
        auto it = epochData.find(epoch);
        if(it != epochData.end())
        {
            vector<string> dataVec = (*it).second;

            if(col >= (dataVec.size()-1) )
            {
                InvalidRequest e(" col not found.");
                GPSTK_THROW(e);
            }
            else
            {
                double value = asDouble(dataVec[col]);
                return value;
            }
        }
        else
        {
            InvalidRequest e(" col not found.");
            GPSTK_THROW(e);
        }
    
    } // END of "getPos"

}

